package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.feign.UserFeign;
import com.heima.article.mapper.*;
import com.heima.article.service.ApArticleService;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.*;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.utils.common.ApUserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多/和加载当前  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {

        //检查参数
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //设置初始页码
        if (null == dto.getSize()) {
            dto.setSize(10);
        }
        if (dto.getSize() > 50) {
            dto.setSize(50);
        }

        //检查时间是否有值
        if (null == dto.getMaxBehotTime()) {
            dto.setMaxBehotTime(new Date());
        }
        if (null == dto.getMinBehotTime()) {
            dto.setMinBehotTime(new Date());
        }

        //查询结果
        List<ApArticle> apArticles = this.apArticleMapper.loadArticleList(dto, loadtype);

        //封装对象 并返回
        return ResponseResult.okResult(apArticles);
    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    /**
     * 加载文章详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {

        //检查参数
        if (null == dto || null == dto.getArticleId()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //检查是否下架
        ApArticleConfig articleConfig = apArticleConfigMapper.selectOne
                (Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, dto.getArticleId()));
        if (null == articleConfig || articleConfig.getIsDown() || articleConfig.getIsDelete()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        //获取文章内容
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne
                (Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getArticleId()));
        if (null == apArticleContent) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        //封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("config", articleConfig);
        map.put("content", apArticleContent);

        //响应数据
        return ResponseResult.okResult(map);
    }

    @Autowired
    private ApCollectionMapper apCollectionMapper;

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private ApAuthorMapper apAuthorMapper;

    /**
     * 加载文章详情的行为内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {

        //检查参数
        if (null == dto || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取登录用户id
        Integer userId = ApUserThreadLocal.getUserId();
        if (null == userId || userId == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //获取行为实体
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        if (null == apBehaviorEntry) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //定义封装对象
        boolean isUnlike = false, isLike = false, isCollection = false, isFollow = false;

        //获取是否点赞
        Integer likeByArticleIdAndEntryId = behaviorFeign.findLikeByArticleIdAndEntryId(apBehaviorEntry.getId(), dto.getArticleId(), (short) 0);
        if (likeByArticleIdAndEntryId > 0) {
            isLike = true;
        }

        //获取是否关注
        ApAuthor apAuthor = apAuthorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getUserId, dto.getAuthorId()));
        if (null != apAuthor) {
            ApUserFollow andFollowId = userFeign.findByUserIdAndFollowId(userId, apAuthor.getId());
            if (null != andFollowId) {
                isFollow = true;
            }
        }

        //获取是否收藏
        Integer selectCount = apCollectionMapper.selectCount(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getEntryId, apBehaviorEntry.getId())
                .eq(ApCollection::getArticleId, dto.getArticleId())
                .eq(ApCollection::getType, 0));
        if (selectCount > 0) {
            isCollection = true;
        }

        //获取是否不喜欢
        Integer unLikeByArticleIdAndEntryId = behaviorFeign.findUnLikeByArticleIdAndEntryId(apBehaviorEntry.getId(), dto.getArticleId(), (short) 0);
        if (unLikeByArticleIdAndEntryId > 0) {
            isUnlike = true;
        }

        //封装参数
        Map<String, Boolean> map = new HashMap<>();
        map.put("isunlike", isUnlike);
        map.put("islike", isLike);
        map.put("iscollection", isCollection);
        map.put("isfollow", isFollow);

        //响应数据
        return ResponseResult.okResult(map);
    }
}
